<template>
	<div>
		<main-content
			:tableHeight.sync="tableHeight"
			:otherDependenComponents="otherDependenComponents"
		>
			<template slot="query">
				<el-form
					ref="form"
					:inline="true"
					:model="queryData"
					class="flex-warp-container"
				>
					<el-form-item
						:label="`${$t('common.belong_merchant')}:`"
						prop="merchantId"
						class="flex-row-container"
						label-width="77px"
					>
						<merchant-select
							v-model="queryData.merchantId"
						></merchant-select>
					</el-form-item>
					<el-form-item label="总代账号:">
						<el-input
							v-model="queryData.topProxyName"
							v-input="{ name: 'symbols' }"
							clearable
							:placeholder="$t('common.please_enter')"
							size="medium"
						></el-input>
					</el-form-item>
					<el-form-item label="合营码:">
						<el-input
							v-input="{ name: 'symbols' }"
							v-model="queryData.joinCode"
							:maxlength="11"
							clearable
							size="medium"
							:placeholder="$t('common.please_enter')"
						></el-input>
					</el-form-item>
					<el-form-item
						label="账号状态:"
						class="flex-row-container"
						label-width="77px"
					>
						<el-select
							v-model="queryData.accountTypes"
							clearable
							multiple
							:placeholder="$t('common.select_all')"
							:popper-append-to-body="false"
						>
							<el-option
								v-for="(item, index) in accountTypesList"
								:key="index"
								:label="item.label"
								:value="item.value"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item
						label="风控状态:"
						class="flex-row-container"
						label-width="77px"
					>
						<el-select
							v-model="queryData.riskControlStatus"
							clearable
							multiple
							:placeholder="$t('common.select_all')"
							:popper-append-to-body="false"
						>
							<el-option
								v-for="(item, index) in riskControlStatusList"
								:key="index"
								:label="item.label"
								:value="item.value"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item
						label="最后修改时间:"
						class="flex-row-container"
						label-width="120px"
					>
						<el-date-picker
							v-model="formTime.time"
							size="medium"
							:picker-options="pickerShortcut2"
							format="yyyy-MM-dd HH:mm:ss"
							type="datetimerange"
							range-separator="-"
							:start-placeholder="$t('common.start_date')"
							:end-placeholder="$t('common.end_date')"
							align="right"
							:clearable="false"
							:default-time="defaultTime"
						></el-date-picker>
					</el-form-item>
					<el-form-item label="最后修改账号:">
						<el-input
							v-input="{ name: 'symbols' }"
							v-model="queryData.updateBy"
							:maxlength="11"
							clearable
							size="medium"
							:placeholder="$t('common.please_enter')"
						></el-input>
					</el-form-item>
					<el-form-item
						label="锁定方式:"
						class="flex-row-container"
						label-width="77px"
					>
						<el-select
							v-model="queryData.netAssetsWindLockType"
							clearable
							:placeholder="$t('common.select_all')"
							:popper-append-to-body="false"
						>
							<el-option
								v-for="(
									item, index
								) in netAssetsWindLockTypeList"
								:key="index"
								:label="item.label"
								:value="item.value"
							></el-option>
						</el-select>
					</el-form-item>
					<el-form-item style="margin-left: 8px">
						<el-button
							type="primary"
							icon="el-icon-search"
							size="medium"
							@click="search"
						>
							{{ $t('common.search') }}
						</el-button>
						<el-button
							icon="el-icon-refresh-left"
							size="medium"
							@click="reset"
						>
							{{ $t('common.reset') }}
						</el-button>
					</el-form-item>
				</el-form>
				<div class="divBox">
					<span class="danger data-refresh">
						{{ $t('funds.fund_audit.data_update_time') }}：
						{{ now }}
					</span>
					<el-select
						v-model="activeTopup"
						size="mini"
						:placeholder="$t('common.please_choose')"
						@change="recordTime"
					>
						<el-option
							v-for="item in timeList"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						></el-option>
					</el-select>
				</div>
			</template>
			<template slot="content">
				<el-table
					v-loading="loading"
					ref="elTable"
					element-loading-spinner="el-icon-loading"
					border
					size="mini"
					class="small-size-table"
					:data="dataList"
					style="width: 100%"
					highlight-current-row
					:header-cell-style="getRowClass"
					:max-height="tableHeight"
					@sort-change="changeTableSort"
				>
					<el-table-column
						prop="proxyName"
						align="center"
						label="总代账号"
						min-width="150"
						show-overflow-tooltip
					>
						<template slot-scope="scope">
							{{ scope.row.proxyName || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						prop="joinCode"
						align="center"
						label="合营码"
						min-width="100"
						show-overflow-tooltip
					>
						<template slot-scope="scope">
							{{ scope.row.joinCode || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						prop="merchantName"
						align="center"
						label="所属商户"
						min-width="150"
						show-overflow-tooltip
					>
						<template slot-scope="scope">
							{{ scope.row.merchantName || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						prop="creditLevel"
						align="center"
						label="信用等级"
						min-width="120"
					>
						<template slot-scope="scope">
							<span>
								{{ getNumberValue(scope.row.creditLevel) }}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="creditLevel"
						align="center"
						label="锁定方式"
						min-width="120"
					>
						<template slot-scope="scope">
							<span v-if="scope.row.netAssetsWindLockType == 1">
								手动锁定
							</span>
							<span v-else>自动锁定</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="accountStatus"
						align="center"
						label="账号状态"
						:min-width="getWidth(100)"
					>
						<template slot-scope="scope">
							<!-- <span
								v-if="!!scope.row.paymentLockStatus"
								class="deleteRgba"
							>
								{{ $t('common.account_lock_status') }}
								<br />
							</span>
							<span
								v-if="!!scope.row.loginLockStatus"
								class="disableRgba"
							>
								{{ $t('common.login_lock_status') }}
								<br />
							</span>
							<span
								v-if="!!scope.row.gameLockStatus"
								class="lockingRgba"
							>
								{{ $t('common.game_lock_status') }}
							</span>
							<span
								v-if="
									scope.row.loginLockStatus === 0 &&
									scope.row.gameLockStatus === 0 &&
									scope.row.paymentLockStatus === 0
								"
								class="normalRgba"
							>
								{{ $t('common.account_status_normal') }}
							</span> -->
							{{ scope.row.accountStatusStr || '-' }}
						</template>
					</el-table-column>
					<el-table-column
						prop="createdAt"
						align="center"
						label="风控状态"
						min-width="120"
						show-overflow-tooltip
					>
						<template slot-scope="scope">
							<el-link
								:underline="false"
								:type="
									riskControlStatusMap[
										scope.row.riskControlStatus
									] &&
									riskControlStatusMap[
										scope.row.riskControlStatus
									].type
								"
							>
								{{
									(riskControlStatusMap[
										scope.row.riskControlStatus
									] &&
										riskControlStatusMap[
											scope.row.riskControlStatus
										].name) ||
									'-'
								}}
							</el-link>
						</template>
					</el-table-column>
					<el-table-column
						prop="afterChipTotal"
						align="center"
						min-width="180"
						show-overflow-tooltip
					>
						<template slot="header">
							<span class="flexBox">
								<span>净资产风控阈值告警/锁定</span>
								<el-tooltip
									class="item"
									effect="dark"
									placement="top-start"
								>
									<span slot="content">
										总代团队净资产低于告警阈值将触发净资产告警，低于锁定阈值将触发净资产锁定。
									</span>
									<i class="el-icon-question"></i>
								</el-tooltip>
							</span>
						</template>
						<template slot-scope="scope">
							<div class="flex-box">
								<el-link
									:underline="false"
									:type="
										scope.row.netAssetsWindAlarmThreshold
											? 'warning'
											: 'primary'
									"
								>
									{{
										handleNumber(
											scope.row.currency,
											scope.row
												.netAssetsWindAlarmThreshold
										)
									}}
								</el-link>
								<span>/</span>
								<el-link
									:underline="false"
									:type="
										scope.row.netAssetsWindLockThreshold
											? 'danger'
											: 'primary'
									"
								>
									{{
										scope.row.netAssetsWindLockType == 1
											? '-'
											: handleNumber(
													scope.row.currency,
													scope.row
														.netAssetsWindLockThreshold
											  )
									}}
								</el-link>
							</div>
						</template>
					</el-table-column>
					<el-table-column
						align="center"
						label="团队净资产"
						sortable
						prop="netAssets"
						min-width="180"
					>
						<template slot-scope="scope">
							<span
								:style="handleNumberColor(scope.row.netAssets)"
							>
								{{
									handleNumber(
										scope.row.currency,
										scope.row.netAssets
									)
								}}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						align="center"
						label="总代押金"
						min-width="180"
					>
						<template slot-scope="scope">
							<span>
								{{
									handleNumber(
										scope.row.currency,
										scope.row.totalAgentDeposit
									)
								}}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						align="center"
						label="授信总额"
						min-width="180"
					>
						<template slot-scope="scope">
							<span>
								{{
									handleNumber(
										scope.row.currency,
										scope.row.teamCreditTotal
									)
								}}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						align="center"
						label="德州场馆盈亏"
						min-width="180"
					>
						<template slot-scope="scope">
							<span
								:style="
									handleNumberColor(
										scope.row.dzVenueNetAmount
									)
								"
							>
								{{
									handleNumber(
										scope.row.currency,
										scope.row.dzVenueNetAmount,
										2,
										true,
										true
									)
								}}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						align="center"
						label="其他场馆盈亏"
						min-width="180"
					>
						<template slot-scope="scope">
							<span
								:style="
									handleNumberColor(
										scope.row.otherVenueNetAmount
									)
								"
							>
								{{
									handleNumber(
										scope.row.currency,
										scope.row.otherVenueNetAmount,
										2,
										true,
										true
									)
								}}
							</span>
						</template>
					</el-table-column>
					<el-table-column
						align="center"
						label="最后修改时间"
						min-width="180"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.updatedAt || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						align="center"
						label="最后修改账号"
						min-width="100"
					>
						<template slot-scope="scope">
							<span>{{ scope.row.updatedBy || '-' }}</span>
						</template>
					</el-table-column>
					<el-table-column
						fixed="right"
						align="center"
						label="操作"
						min-width="400"
					>
						<template slot-scope="scope">
							<el-button
								v-if="
									hasPermission('90930059') &&
									scope.row.riskControlStatus !== 1 &&
									scope.row.netAssetsWindLockType == 1
								"
								@click="handleLock(scope.row)"
								type="text"
								size="small"
							>
								净资产锁定
							</el-button>
							<el-button
								v-if="
									hasPermission('90870066') &&
									scope.row.riskControlStatus == 1
								"
								@click="handleUnlock(scope.row)"
								type="text"
								size="small"
							>
								解除锁定
							</el-button>
							<el-button
								v-if="hasPermission('90870067')"
								@click="handleRiskControlSettings(scope.row)"
								type="text"
								size="small"
							>
								风控设置
							</el-button>
							<el-button
								v-if="hasPermission('90870068')"
								@click="handleModificationRecord(scope.row)"
								type="text"
								size="small"
							>
								修改记录
							</el-button>
							<el-button
								v-if="hasPermission('90870069')"
								@click="handleRiskControlRecords(scope.row)"
								type="text"
								size="small"
							>
								风控记录
							</el-button>
						</template>
					</el-table-column>
				</el-table>
				<!-- 分页 -->
				<el-pagination
					:current-page.sync="pageNum"
					class="pageValue"
					v-show="!!total"
					background
					layout="total, sizes,prev, pager, next, jumper"
					:page-size="pageSize"
					:page-sizes="pageSizes"
					:total="total"
					:pager-count="9"
					@current-change="handleCurrentChange"
					@size-change="handleSizeChange"
				></el-pagination>
			</template>
		</main-content>
		<GoogleKeyInput
			:isShowdialog="isShowdialog"
			@getGoogleKey="getGoogleKey($event)"
			@backPrevStep="backPrevStep()"
		></GoogleKeyInput>
		<RiskControlSettings
			v-if="showRiskControlSettings"
			:visible.sync="showRiskControlSettings"
			:curData="curData"
			:netAssetsWindLockTypeList="netAssetsWindLockTypeList"
			@editSuccess="loadData"
		/>
		<ModificationRecord
			v-if="showModificationRecord"
			:visible.sync="showModificationRecord"
			:curData="curData"
		/>
	</div>
</template>

<script>
import list from '@/mixins/list'
import dayjs from 'dayjs'
import MainContent from '@/components/MainContent/index.vue'
import RiskControlSettings from './components/RiskControlSettings'
import ModificationRecord from './components/ModificationRecord'

export default {
  components: {
    MainContent,
    RiskControlSettings,
    ModificationRecord,
    GoogleKeyInput: () => import('@/components/GoogleKeyInput')
  },
  mixins: [list],
  data() {
    return {
      curData: {},
      showModificationRecord: false,
      showRiskControlSettings: false,
      isShowdialog: false,
      ruleFormType: '',
      tableHeight: 480,
      otherDependenComponents: [],
      queryData: {
        topProxyName: '',
        joinCode: '',
        accountTypes: [],
        riskControlStatus: [],
        updateBy: '',
        sortType: '',
        sortValue: '',
        netAssetsWindLockType: ''
      },
      dataList: [],
      now: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
      timeList: [],
      agentTopupTimer: null,
      activeTopup: this.$t('funds.fund_audit.no_reload'),
      formTime: {
        time: []
      },
      accountTypesList: [
        {
          label: '正常',
          value: 1
        },
        {
          label: '登录锁定',
          value: 2
        },
        {
          label: '充提锁定',
          value: 3
        }
      ],
      riskControlStatusList: [
        {
          label: '正常',
          value: 0
        },
        {
          label: '净资产告警',
          value: 2
        },
        {
          label: '净资产锁定',
          value: 1
        }
      ],
      riskControlStatusMap: {
        0: {
          type: 'primary',
          name: '正常'
        },
        2: {
          type: 'warning',
          name: '净资产告警'
        },
        1: {
          type: 'danger',
          name: '净资产锁定'
        }
      },
      netAssetsWindLockTypeList: [
        {
          label: '自动锁定',
          value: 0
        },
        {
          label: '手动锁定',
          value: 1
        }
      ]
    }
  },
  created() {
    if (this.hasPermission('407051') || this.hasPermission('407052')) {
      this.getKvconfigList()
    }
  },
  mounted() {
  },
  activated() {
    if (
      Number(this.activeTopup) &&
      (this.hasPermission('407051') || this.hasPermission('407052'))
    ) {
      this.agentTopupTimer = setInterval(
        this.loadData,
        this.activeTopup * 1000
      )
    } else {
      clearInterval(this.agentTopupTimer)
    }
  },
  deactivated() {
    clearInterval(this.agentTopupTimer)
  },
  beforeDestroy() {
    clearInterval(this.agentTopupTimer)
    this.agentTopupTimer = null
  },
  methods: {
    getGoogleKey(data) {
      this.isShowdialog = false
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      if (this.ruleFormType === 'unlock') {
        const params = {
          //   merchantId: this.curData.merchantId,
          //   topProxyName: this.curData.proxyName,
          id: this.curData.id,
          haiyueAuthCode: data
        }
        this.$api.windControllerCreditProxyUnlock(params)
          .then((res) => {
            if (res.code === 200) {
              this.$message.success(
                this.$t('common.action_success')
              )
              this.loadData()
              this.visibleDialog = false
            }
            loading.close()
          })
          .catch(() => {
            loading.close()
          })
      } else if (this.ruleFormType === 'handleUnlock') {
        const params = {
          //   merchantId: this.curData.merchantId,
          //   topProxyName: this.curData.proxyName,
          id: this.curData.id,
          haiyueAuthCode: data
        }
        this.$api.windControllerCreditProxyHandUnLock(params)
          .then((res) => {
            if (res.code === 200) {
              this.$message.success(
                this.$t('common.action_success')
              )
              this.loadData()
              this.visibleDialog = false
            }
            loading.close()
          })
          .catch(() => {
            loading.close()
          })
      } else if (this.ruleFormType === 'handleLock') {
        const params = {
          //   merchantId: this.curData.merchantId,
          //   topProxyName: this.curData.proxyName,
          id: this.curData.id,
          haiyueAuthCode: data
        }
        this.$api.windControllerCreditProxyHandLock(params)
          .then((res) => {
            if (res.code === 200) {
              this.$message.success(
                this.$t('common.action_success')
              )
              this.loadData()
              this.visibleDialog = false
            }
            loading.close()
          })
          .catch(() => {
            loading.close()
          })
      }
    },
    backPrevStep() {
      this.isShowdialog = false
    },
    // 净资产锁定
    handleLock(val) {
      this.$confirm(
        '净资产锁定后，代理线所有代理及会员提现及游戏功能将受到限制。是否确认锁定？', '净资产锁定', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.ruleFormType = 'handleLock'
        this.curData = val
        this.isShowdialog = true
      }).catch(() => {

      })
    },
    // 解除锁定
    handleUnlock(val) {
      this.$confirm(
        val.netAssetsWindLockType == 0 ? '仅当总代团队净资产＞净资产风控锁定阈值，可以解除净资产锁定。解锁后，代理线所有代理及会员提现及游戏功能恢复正常。是否确认解锁？' : '解锁后，代理线所有代理及会员提现及游戏功能恢复正常。是否确认解锁？', '解除净资产锁定', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (val.netAssetsWindLockType == 0) {
          this.ruleFormType = 'unlock'
        } else {
          this.ruleFormType = 'handleUnlock'
        }
        this.curData = val
        this.isShowdialog = true
      }).catch(() => {

      })
    },
    // 风控设置
    handleRiskControlSettings(val) {
      this.curData = val
      this.showRiskControlSettings = true
    },
    // 修改记录
    handleModificationRecord(val) {
      this.curData = val
      this.showModificationRecord = true
    },
    //   风控记录
    handleRiskControlRecords(val) {
      this.$router.push(`/risk/riskManage/agentRiskControlRecords?proxyName=${val.proxyName}`)
    },
    changeTableSort({ column, prop, order }) {
      this.queryData.sortType = prop
      if (order === 'ascending') {
        // 升序
        this.queryData.sortValue = 0
      } else if (column.order === 'descending') {
        // 降序
        this.queryData.sortValue = 1
      } else {
        delete this.queryData.sortType
        delete this.queryData.sortValue
      }
      this.loadData()
    },
    recordTime(val) {
      this.activeTopup = val
      if (Number(val)) {
        clearInterval(this.agentTopupTimer)
        this.agentTopupTimer = setInterval(this.loadData, val * 1000)
      } else {
        clearInterval(this.agentTopupTimer)
      }
    },
    getKvconfigList() {
      this.timeList = []
      let str = ''
      let arr = []
      const params = {
        k: 'funds.audit.pagerefresh.interval.config',
        pageNum: 1,
        pageSize: 10
      }
      this.$api.getkvconfigQueryList(params).then((res) => {
        if (res.code === 200 && res.data) {
          const val = res.data.records[0] || []
          if (val.v) {
            str = val.v
            arr = str.split(',').sort()
            arr.forEach((item, index) => {
              const obj = {}
              if (Number(item) === 0) {
                obj.label = this.$t(
                  'funds.fund_audit.no_reload'
                )
                obj.value = this.$t(
                  'funds.fund_audit.no_reload'
                )
                this.timeList.push(obj)
                this.activeTopup = this.$t(
                  'funds.fund_audit.no_reload'
                )
                this.agentTopupTimer = null
              } else if (Number(item)) {
                obj.label =
                  item + this.$t('funds.fund_audit.second')
                obj.value = item
                this.timeList.push(obj)
              }
            })
          }
        }
      })
    },
    loadData() {
      const [startTime, endTime] = this.formTime.time || []
      let params = {
        ...this.queryData,
        updatedAtBegin: startTime
          ? dayjs(startTime).format('YYYY-MM-DD HH:mm:ss')
          : undefined,
        updatedAtEnd: endTime
          ? dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')
          : undefined
      }
      params = {
        ...this.getParams(params)
      }
      this.loading = true
      this.$api.windControllerCreditProxyList(params)
        .then((res) => {
          if (res.code === 200) {
            this.now = dayjs(new Date()).format(
              'YYYY-MM-DD HH:mm:ss'
            )
            const { record, totalRecord } = res.data || {}
            this.dataList = record || []
            this.total = totalRecord || 0
            if (this.dataList) {
              this.dataList.forEach((item) => {
                item.lockOrder =
                  Number(item.lockStatus) === 1
              })
            }
            this.loading = false
          } else {
            this.loading = false
            this.$message({
              message: res.msg,
              type: 'error'
            })
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    search() {
      this.pageNum = 1
      clearInterval(this.agentTopupTimer)
      this.agentTopupTimer = null
      if (Number(this.activeTopup)) {
        this.agentTopupTimer = setInterval(
          this.loadData,
          this.activeTopup * 1000
        )
      }
      this.loadData()
    },
    reset() {
      this.queryData = {
        topProxyName: '',
        joinCode: '',
        accountTypes: [],
        riskControlStatus: [],
        updateBy: '',
        sortType: '',
        sortValue: '',
        netAssetsWindLockType: ''
      }
      this.formTime = {
        time: []
      }
      if (this.$refs.elTable) {
        this.$refs.elTable.clearSort()
      }
      this.search()
    },
    handleCurrentChange(val) {
      this.pageNum = val
      clearInterval(this.agentTopupTimer)
      this.agentTopupTimer = null
      if (Number(this.activeTopup)) {
        this.agentTopupTimer = setInterval(
          this.loadData,
          this.activeTopup * 1000
        )
      }
      this.loadData()
    },
    handleSizeChange(val) {
      this.pageSize = val
      clearInterval(this.agentTopupTimer)
      this.agentTopupTimer = null
      if (Number(this.activeTopup)) {
        this.agentTopupTimer = setInterval(
          this.loadData,
          this.activeTopup * 1000
        )
      }
      this.loadData()
    }
  }
}
</script>

<style lang="scss" scoped>
.divBox {
	display: flex;
	.el-select {
		width: 100px;
	}
}
.data-refresh {
	margin-top: 0;
	padding-bottom: 20px;
	line-height: 28px;
	margin-right: 20px;
}
::v-deep .el-icon-question:after {
	font-size: 12px;
	margin-left: 0;
}
.flex-box {
	display: flex;
	align-items: center;
	justify-content: center;
}
</style>
